import re

# 1.match() 从头开始匹配
print('-'*20,'match','-'*20)
m1 = re.match('foo','food')
print(m1.group())
m2 = re.match('foo','seafood')
print(m2)

# 2.search() 从任意位置开始匹配
print('-'*20,'search','-'*20)
s1 = re.search('foo','food')
print(s1)
s2 = re.search('foo','seafood')
print(s2)

# 3.findall() 找到所有匹配的子串
print('-'*20,'replace','-'*20)
f1 = re.findall('ab','abc')
print(f1)
f2 = re.findall('ef','abcd')
print(f2)
f3 = re.findall('ab','ababc')
print(f3)

# 4. finditer() 返回一个迭代器，可以遍历所有匹配的子串
print('-'*20,'finditer','-'*20)
fi1 = re.finditer('ab','abc')
print(fi1)
for i in fi1:
    print(i)
fi2 = re.finditer('ab','ababc')
print(fi2)
for i in fi2:
    print(i)

# 5.sub() 替换字符串  不会改变原字符串，而是返回一个新的字符串
# pattern: 正则表达式 repl:要替换成的字符串 string:要匹配的字符串
print('-'*20,'sub','-'*20)
text = 'hello world'
print(re.sub('world','python',text))
